package com.ourteam.product.requirement.api;

import org.squirrelframework.foundation.fsm.annotation.StateMachineParameters;
import org.squirrelframework.foundation.fsm.annotation.Transit;
import org.squirrelframework.foundation.fsm.annotation.Transitions;
import org.squirrelframework.foundation.fsm.impl.AbstractUntypedStateMachine;

import com.ourteam.product.requirement.domain.ProductIssueChangeLogBean;
import com.ourteam.product.requirement.service.IProductIssueService;
import com.ourteam.product.requirement.service.ProductIssueServiceFactory;

enum UserRequirementEvent {
	submitProductIssue, acceptProductIssue, rejectProductIssue, closeProductIssue
}

enum UserRequirementState {
	unsubmitted, submitted, accepted, rejected, closed
}

@Transitions({ @Transit(from = "unsubmitted", to = "submitted", on = "submitProductIssue", callMethod = "stateChanged"),
		@Transit(from = "submitted", to = "accepted", on = "acceptProductIssue", callMethod = "stateChanged", whenMvel = "CheckProductRole:::(context!=null && context.operatorRole == 'PRODUCT_MANAGER')"),
		@Transit(from = "submitted", to = "rejected", on = "rejectProductIssue", callMethod = "stateChanged", whenMvel = "CheckProductRole:::(context!=null && context.operatorRole == 'PRODUCT_MANAGER')"),
		@Transit(from = "accepted", to = "closed", on = "closeProductIssue", callMethod = "stateChanged", whenMvel = "CheckProductRole2:::(context!=null && context.operatorId == context.productIssueBean.creatorId)"),
		@Transit(from = "rejected", to = "closed", on = "closeProductIssue", callMethod = "stateChanged", whenMvel = "CheckProductRole2:::(context!=null && context.operatorId == context.productIssueBean.creatorId)"),
		@Transit(from = "submitted", to = "closed", on = "closeProductIssue", callMethod = "stateChanged", whenMvel = "CheckProductRole2:::(context!=null && context.operatorId == context.productIssueBean.creatorId)") })
@StateMachineParameters(stateType = UserRequirementState.class, eventType = UserRequirementEvent.class, contextType = UserRequirementStateMachineContext.class)
public class UserRequirementStateMachine extends AbstractUntypedStateMachine {

	private static final IProductIssueService PRODUCT_ISSUE_SERVICE = ProductIssueServiceFactory
			.getProductIssueService();

	protected void stateChanged(UserRequirementState from, UserRequirementState to, UserRequirementEvent event,
			UserRequirementStateMachineContext context) throws Exception {

		ProductIssueChangeLogBean changeLogBean = new ProductIssueChangeLogBean();

		changeLogBean.setBeforeChangeStatus(from.name());
		changeLogBean.setAfterChangeStatus(to.name());
		changeLogBean.setProducrIssueId(context.getProductIssueBean().getId());
		changeLogBean.setOperatorId(context.getOperatorId());
		changeLogBean.setRemarks(context.getOperateRemarks());

		PRODUCT_ISSUE_SERVICE.addNewProductIssueChangeLog(changeLogBean);
	}
}
